package tech.nuoson.wisdom.infra.internal.ydaospeechtrans;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import tech.nuoson.wisdom.domain.foundationmodel.ApiErrorCode;
import tech.nuoson.wisdom.domain.foundationmodel.BusinessException;

public class YdaoAuthUtils {

    /**
     * 
     * @param appKey
     * @param appSecret
     * @return
     */
    public static YdaoV4SignResult getV4Sign(String appKey, String appSecret) {
        String salt = UUID.randomUUID().toString();
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String stringToSign = String.join("", appKey, salt, timestamp, appSecret);
        String sign = encrypt(stringToSign);
        return new YdaoV4SignResult(appKey, salt, sign, timestamp);
    }

    /**
     * 
     * @param strSrc
     * @return
     */
    private static String encrypt(String strSrc) {
        try {
            byte[] bt = strSrc.getBytes();
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(bt);
            byte[] bts = md.digest();
            StringBuilder des = new StringBuilder();
            for (byte b : bts) {
                String tmp = (Integer.toHexString(b & 0xFF));
                if (tmp.length() == 1) {
                    des.append("0");
                }
                des.append(tmp);
            }
            return des.toString();
        } catch (NoSuchAlgorithmException ex) {
            throw new BusinessException(ApiErrorCode.GeneralErrorCodeEnum.FAILED, ex);
        }
    }
}
